﻿using CoreShop.App.Controls;
using CoreShop.App.Properties;
using CoreShop.App.Scale;
using CoreShop.App.Test;
using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.PrintService;
using CoreShop.Services;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using static CoreShop.Library.GlobalEnumVars;


namespace CoreShop.App
{
    public partial class FOrdering : UIPage
    {
        public FOrdering()
        {
            InitializeComponent();
            this.gridLastBill.AutoGenerateColumns = false;
            this.txtInput.DoValueChanged += DoValueChanged;            
            if (timer_focus == null)
            {
                timer_focus = new System.Timers.Timer();
                timer_focus.Interval = 200;
                timer_focus.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
                timer_focus.Enabled = true;
            }

            // 初始化定时器
            if (sysDateTime == null)
            {
                sysDateTime = new Sunny.UI.UIMillisecondTimer();
                sysDateTime.Tick += new EventHandler(SysDateTimeTimer_Tick);
                sysDateTime.Interval = 10000; // 设置时间间隔为10秒
                sysDateTime.Enabled = true;
                sysDateTime.Start(); // 启动定时器
            }
        }
       
        public corecmsfoodorderingmaster orderingMaster = null;
        public List<corecmsfoodordering> orderingDetail = null;
        public corecmsfoodordering orderingSelected = null;
        private UIMenuItem uiMenuItemSelected = null;
        public corecmsuser orderingMember = null;
        public corecmsemployee orderingEmployee = null;
        private bool isFocusInput = false;
        static System.Timers.Timer timer_focus = null;
        /// <summary>
        /// 更新时间
        /// </summary>
        Sunny.UI.UIMillisecondTimer sysDateTime = null;

        #region AI相关
        /// <summary>
        /// AI商品选择
        /// </summary>
        frmFoodListAI aIProductSelect = null;
        private void GreateAIForm()
        {
            if (AppConstVars.systemsetup.aiType> 0)
            {
                if (aIProductSelect == null || aIProductSelect.IsDisposed)
                {
                    this.Refresh();
                    ShowWaitForm("AI设备初始化中，请稍等...");
                    try
                    {
                        aIProductSelect = new frmFoodListAI();
                        //aIProductSelect.Height = this.Height;
                        //aIProductSelect.Width = this.Width;
                        //aIProductSelect.Top = 0;
                        //aIProductSelect.Left = 0;
                        aIProductSelect.Owner = this;                        
                        aIProductSelect.Show();
                        aIProductSelect.Hide();
                    }
                    catch (Exception ex)
                    {
                        HideWaitForm();
                        MessageBox.Show("错误：" + ex.Message);
                    }
                    finally
                    {
                        HideWaitForm();
                    }
                }
            }
        }

        public void SetWeighQty(decimal dQty)
        {
            this.lblScaleQty.Text = (dQty * AppConstVars.mConvert).ToString();
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="msg"></param>
        public void A_SetLog(string msg)
        {
            //try
            //{
            //    this.rtb_log.Invoke(new Action(() =>
            //    {
            //        if (this.rtb_log.Text.Length > 5000) rtb_log.Text = String.Empty;
            //        this.rtb_log.AppendText(msg);
            //        this.rtb_log.HideSelection = false;
            //    }));
            //}
            //catch (Exception ex) { }
        }

        private bool AI_SetFormHideFlag()
        {
            if (AppConstVars.systemsetup.aiType == (int)GlobalEnumVars.AiType.None) return true;
            decimal sScaleQty = CommFunc.ConvertToDecimal(lblScaleQty.Text);

            if ((int)(sScaleQty * 1000) < AppConstVars.systemsetup.starWeight)
            {
                aIProductSelect.sAI_WeighQty = 0;
                aIProductSelect.Hide();
                A_SetLog("aIProductSelect.Hide()");
                return true;
            }
            return false;
        }

        private void AI_SetReboot()
        {
            try
            {
                A_SetLog("AI_SetReboot");
                if (AppConstVars.systemsetup.aiType == (int)GlobalEnumVars.AiType.None) return;
                decimal sScaleQty = CommFunc.ConvertToDecimal(lblScaleQty.Text);

                if ((int)(sScaleQty * 1000) < AppConstVars.systemsetup.starWeight)
                {
                    aIProductSelect.sAI_WeighQty = 0;
                    aIProductSelect.Hide();
                    A_SetLog("aIProductSelect.Hide()");
                    return;
                }

                decimal mScaleDiff = Math.Abs(sScaleQty - aIProductSelect.sAI_WeighQty) * 1000;
                if ((mScaleDiff > AppConstVars.systemsetup.starWeight) && (aIProductSelect.sAI_WeighQty <= 0) && (CommFunc.ConvertToString(lblScaleQty.Tag) == "True"))
                {
                    aIProductSelect.sAI_WeighQty = sScaleQty;
                    A_SetLog(string.Format("aIProductSelect.sAI_WeighQty={0}", sScaleQty));
                    Thread.Sleep(500);
                    aIProductSelect.AI_SendMsg("21", "", "");
                }
            }
            catch (Exception ex)
            {

            }
        }

        #endregion

        #region Timer相关
        public void TimerFocusState(bool isEnabled)
        {
            timer_focus.Enabled = isEnabled;
            if (!isEnabled) txtInput.HideDropDown();
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (!isFocusInput)
                {
                    this.txtInput.Invoke(new Action(() =>
                    {
                        this.txtInput.Focus();
                    }));
                }

            }
            catch { }
        }

        /// <summary>
        /// 电子秤串口状态
        /// </summary>
        public void GetComportState()
        {
            try
            {
                if (AppConstVars.mScaleType == 0) return;
                this.Invoke(new Action(() =>
                {
                    bool onLine = false;
                    if (AppConstVars.mScaleType == (int)GlobalEnumVars.ScaleType.DJ_OS2_Dll)
                    {
                        if (Program.frmMainWin.scaleModel != null) onLine = Program.frmMainWin.scaleModel.OnLine;
                    }
                    else
                        if ((Program.frmMainWin.comport != null) && (Program.frmMainWin.comport.IsOpen))  onLine = true;
                    if (onLine.ToString() != CommFunc.ConvertToString(this.btnComportState.Tag))
                    {
                        if (onLine)
                            this.btnComportState.BackColor = Color.LimeGreen;
                        else
                            this.btnComportState.BackColor = Color.Salmon;
                        this.btnComportState.Tag = onLine.ToString();
                    }                       
                }));
            }
            catch { }
        }

        public void SysDateTimeTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    if (this.lblSysTime.Text != DateTime.Now.ToString("HH:mm"))
                    {
                        this.lblSysTime.Text = DateTime.Now.ToString("HH:mm");
                    }
                    if (this.lblSysDate.Text != DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        this.lblSysDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    }
                    GetComportState();
                }));
            }
            catch { }
        }

        #endregion

        #region 控件机关

        /// <summary>
        /// 根据指定容器和控件名字，获得控件
        /// </summary>
        /// <param name="obj">容器</param>
        /// <param name="strControlName">控件名字</param>
        /// <returns>控件</returns>
        private object GetControlInstance(object obj, string strControlName)
        {
            IEnumerator Controls = null;//所有控件
            Control c = null;//当前控件
            Object cResult = null;//查找结果
            if (obj.GetType() == this.GetType())//窗体
            {
                Controls = this.Controls.GetEnumerator();
            }
            else//控件
            {
                Controls = ((Control)obj).Controls.GetEnumerator();
            }
            while (Controls.MoveNext())//遍历操作
            {
                c = (Control)Controls.Current;//当前控件
                if (c.HasChildren)//当前控件是个容器
                {
                    cResult = GetControlInstance(c, strControlName);//递归查找
                    if (cResult == null)//当前容器中没有，跳出，继续查找
                        continue;
                    else//找到控件，返回
                        return cResult;
                }
                else if (c.Name == strControlName)//不是容器，同时找到控件，返回
                {
                    return c;
                }
            }
            return null;//控件不存在
        }

        private string GetMenuItemName(long orderingId)
        {
            return "uiMenuItem_" + orderingId.ToString();
        }

        private void SetBindFoodList(object sender, EventArgs e)
        {
            long mFoodTypeId = CommFunc.ConvertToBigInt(sender);
            BindFoodList(mFoodTypeId);
        }
        #endregion      

        private async void FOrdering_LoadAsync(object sender, EventArgs e)
        {
            pnlLogo.Text = string.Empty;
            layFoodType.SetCreateFoodType = true;
            LoadOrderingPara();
            CreateFoodList();
            layFoodType.SetBindFoodList += SetBindFoodList;
            //Program.frmMainWin.setWeighQty += SetWeighQty;
            SysDateTimeTimer_Tick(null,null);
            btnOrderHand.TipsText = await OrderingUtil.GetHangupsCount();            
        }

        private void DoValueChanged(object sender, System.EventArgs e)
        {
            //SetSearch();
        }

        private void LoadOrderingPara()
        {
            if (AppConstVars.sysStore != null)
                this.lblStoreName.Text = AppConstVars.sysStore.storeName;
            this.lblUserName.Text = AppConstVars.sysUser.userName;
            pnl_left_employee.Visible = false;
            uiMemberInfo.Visible = false;
            if (AppConstVars.systemsetup.employeeSelType != (int)GlobalEnumVars.EmployeeSelType.None)
                pnl_left_employee.Visible = true;
            if (AppConstVars.mConvert == 1)
                lblScaleTitle.Text = "重量(kg)";
            else
                lblScaleTitle.Text = "重量(斤)";
            if (AppConstVars.mScaleType == (int)GlobalEnumVars.ScaleType.DJ_OS2_Dll) btnSetZero.Visible = true;
            if (!AppConstVars.systemsetup.paraPartialModel.mobilePayOnPos)
                txtInput.Watermark = "扫商品条码/编码";
            this.btnCashPay.Text = EnumHelper.GetDescByValue<GlobalEnumVars.QuickPayType>(AppConstVars.systemsetup.paraPartialModel.quickPayType);
        }

        private void Form1_Shown(object sender, System.EventArgs e)
        {        
            BindFoodList(0);
            GreateAIForm();
        }

        #region 商品列表相关
        /// <summary>
        /// 商品按钮名称
        /// </summary>
        /// <param name="deskId"></param>
        /// <returns></returns>
        private string GetFoodItemName(int index)
        {
            return "uiFoodItem_" + index.ToString();
        }

        /// <summary>
        /// 建空的单个商品按钮
        /// </summary>
        /// <param name="index"></param>
        private void CreateFoodListBtn(int index)
        {
            DishItemInfo dish = new DishItemInfo();
            dish.Name = "";
            //dish.Money = food.posPrice.ToString()+"/"+ food.foodSpecName;
            dish.Money = "";
            dish.UnitName = "";
            //if (food.isHeft.ObjToBool())
            //{
            //    dish.LabelExist = "剩 10,000 份";
            //    dish.DiscountString = "3个优惠";
            //}
            var item = new UIDishItem(dish);
            item.Name = GetFoodItemName(index);
            item.Visible = false;
            if (AppConstVars.systemsetup.showFoodImg) item.Image = Resources.addprinter;
            //item.TipsText = RandomEx.RandomNumber(1);
            item.Margin = new System.Windows.Forms.Padding(3);
            item.Tag = "";
            item.Click += Item_Click;
            item.MouseDown += Item_MouseDown;
            fly_foodlist.Add(item);
        }

        /// <summary>
        /// 建商品分布按钮
        /// </summary>
        /// <param name="index"></param>
        private void CreateFoodPaper()
        {
            var item = new UIGoodsPagination();
            item.ShowFoodImg = AppConstVars.systemsetup.showFoodImg;
            item.Name = GetFoodItemName(999);
            item.Visible = false;
            item.Margin = new System.Windows.Forms.Padding(3);
            item.SetFoodListPre += SetFoodListPre;
            item.SetFoodListNext += SetFoodListNext;
            fly_foodlist.Add(item);
        }

        /// <summary>
        /// 商品列表上一页(传递给layFoodType)
        /// </summary>
        /// <param name="index"></param>
        private void SetFoodListPre(object sender, EventArgs e)
        {
            layFoodType.SetFoodPre();
        }

        /// <summary>
        /// 商品列表上一页(传递给layFoodType)
        /// </summary>
        /// <param name="index"></param>
        private void SetFoodListNext(object sender, EventArgs e)
        {
            layFoodType.SetFoodNext();
        }

        /// <summary>
        /// 建空的商品按钮
        /// </summary>
        private void CreateFoodList()
        {
            fly_foodlist.Clear();
            DishItemInfo dish = new DishItemInfo();
            dish.Name = "默认";
            dish.Money = "0.00";
            dish.UnitName = "";
            var item = new UIDishItem(dish);

            if (AppConstVars.systemsetup.showFoodImg) item.Image = Resources.addprinter;
            item.Margin = new System.Windows.Forms.Padding(3);
            decimal itemCols = (fly_foodlist.Width - 10) / (item.Width + 3);
            decimal itemRows = (fly_foodlist.Height - 10) / (item.Height + 3);

            layFoodType.SetFoodPageSize(CommFunc.ConvertToInt32(Math.Floor(itemCols)) * CommFunc.ConvertToInt32(Math.Floor(itemRows)));
            for (int i = 1; i <= layFoodType.GetFoodPageSize; i++)
            {
                CreateFoodListBtn(i);
            }
            if (AppConstVars.systemsetup.foodTypeBindType >= (int)GlobalEnumVars.FoodTypeBindType.ParentAndChild)
            {
                CreateFoodPaper();
            }
        }

        /// <summary>
        /// 暂不显示所有商品商品
        /// </summary>
        private void HiddenFoodList(int starIndex)
        {
            for (int i = starIndex; i <= layFoodType.GetFoodPageSize; i++)
            {
                var mControl = fly_foodlist.Get(GetFoodItemName(i));
                var item = (UIDishItem)mControl;
                if (item != null) item.Visible = false;
            }
        }

        private Expressionable<corecmsfood, corecmsfoodspec> GetExpressionable(long mFoodTypeId)
        {
            var where = Expressionable.Create<corecmsfood, corecmsfoodspec>();
            where = where.And((f, s) => f.isDelete == false && f.sellStatus != 0 && s.onLine == true);
            //where = where.And((f, s) => f.isDelete == false && f.sellStatus != 0);
            string sName = txtInput.Text;
            if (!string.IsNullOrEmpty(sName))
                where = where.And((f, s) => f.name.Contains(sName) || f.number.Contains(sName) || s.code.Contains(sName)
                || f.byName.Contains(sName) || f.helpCode.Contains(sName) || f.pinYin.Contains(sName));
            
            if (mFoodTypeId > 0)
            {
                var typeIds = new corecmsfoodcategoryServices().GetChildrenIds(mFoodTypeId);

                if (typeIds.Count > 0)
                    where = where.And((f, s) => f.foodTypeId == mFoodTypeId || typeIds.Contains(f.foodTypeId));
                else
                    where = where.And((f, s) => f.foodTypeId == mFoodTypeId);
            }

            return where;
        }

        /// <summary>
        /// 判断是最后的清空且有数据，不刷新
        /// </summary>
        /// <returns></returns>
        private bool IsClearText()
        {
            string sName = txtInput.Text;
            if (sName.IsNullOrEmpty())
            {                
                var mControl = fly_foodlist.Get(GetFoodItemName(2));
                var item = (UIDishItem)mControl;
                if ((item != null) && item.Visible) return true;//清空text数据，且有数据，不重新刷新数据
            }
            //Program.frmMainWin.A_SetLog(sName+"\n");
            return false;
        }

        private void BindFoodList(long mFoodTypeId, int keyValue = 0)
        {
            int mFoodRowCount = 0;
            int mFoodPageSize = layFoodType.GetFoodPageSize;

            //如果显示大小类，商品的分类按钮在最后一个
            if (AppConstVars.systemsetup.foodTypeBindType >= (int)GlobalEnumVars.FoodTypeBindType.ParentAndChild)
                mFoodPageSize = layFoodType.GetFoodPageSize - 1;

            var foodList = new corecmsfoodServices().QueryPageAsync(ref mFoodRowCount, layFoodType.FoodPageIndex, mFoodPageSize, GetExpressionable(mFoodTypeId));
            layFoodType.FoodRowCount = mFoodRowCount;
            int index = 1;
            var orderingUnit = new OrderingUtil();
            fly_foodlist.Visible = false;
            AppConstVars.isDownLoadFile = false;
            this.fly_foodlist.SuspendLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
            foreach (var food in foodList)
            {
                var mControl = fly_foodlist.Get(GetFoodItemName(index));
                var item = (UIDishItem)mControl;
                if (item != null)
                {
                    item.Tag = food.id.ToString();
                    item.Visible = true;
                    item.TextName = food.name;
                    var dish = item.Info;
                    dish.Name = food.name;
                    dish.Money = food.posPrice.ToString();
                    dish.UnitName = food.foodUnitName;
                    item.SetEnabled();
                    OrderingUtil.SetDishItemImage(item, food);//加载商品图片                    
                    item.Refresh();
                }
                index++;
            }
            HiddenFoodList(index);

            if (AppConstVars.systemsetup.foodTypeBindType >= (int)GlobalEnumVars.FoodTypeBindType.ParentAndChild)
            {
                var pgControl = fly_foodlist.Get(GetFoodItemName(999));
                var itemPage = (UIGoodsPagination)pgControl;
                if (itemPage != null) itemPage.Visible = layFoodType.FoodRowCount > layFoodType.GetFoodPageSize;
            }

            this.fly_foodlist.ResumeLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
            fly_foodlist.Visible = true;
            fly_foodlist.Refresh();
            SetFoodPageState();
            downLoadStart();
            //new corecmsfoodsoldoutServices().RecoverySoldout((int)GlobalEnumVars.SoldoutType.Day, foodSoldouts);
        }

        /// <summary>
        /// 刷新已显示的单价
        /// </summary>
        /// <param name="foodList"></param>
        public void BindFoodRefresh(List<corecmsfood> foodList)
        {
            if ((foodList == null) || (foodList.Count == 0)) return;
            this.Invoke(new Action(() =>
            {
                var mControl1 = fly_foodlist.Get(GetFoodItemName(1));
                var item1 = (UIDishItem)mControl1;
                if ((item1 != null) && (item1.Visible == false))
                {
                    BindFoodList(0);
                    return;
                }
                for (int index = 1; index <= layFoodType.GetFoodPageSize; index++)
                {
                    var mControl = fly_foodlist.Get(GetFoodItemName(index));
                    var item = (UIDishItem)mControl;
                    if ((item != null) && item.Visible) 
                    {
                        long foodId = CommFunc.ConvertToBigInt(item.Tag);
                        var food = foodList.Find(p=>p.id == foodId);
                        if (food != null)
                        {
                            var dish = item.Info;
                            dish.Name = food.name;
                            dish.Money = food.posPrice.ToString();
                            dish.UnitName = food.foodUnitName;
                            item.SetEnabled();
                            OrderingUtil.SetDishItemImage(item, food);//加载商品图片                    
                            item.Refresh();
                        }
                    }
                }
            }));            
        }

        /// <summary>
        /// 刷新已显示的单价
        /// </summary>
        /// <param name="foodList"></param>
        public void BindFoodImage(long foodId)
        {
            this.Invoke(new Action(() =>
            {
                for (int index = 1; index <= layFoodType.GetFoodPageSize; index++)
                {
                    var mControl = fly_foodlist.Get(GetFoodItemName(index));
                    var item = (UIDishItem)mControl;
                    if ((item != null) && item.Visible)
                    {
                        if (CommFunc.ConvertToInt64(item.Tag) == foodId)
                        {
                            var food = new corecmsfoodServices().GetById(foodId);
                            if (food != null)
                            {
                                OrderingUtil.SetDishItemImage(item, food);//加载商品图片                    
                                item.Refresh();
                            }
                        }
                    }
                }
            }));
        }

        private void downLoadStart()
        {
            if (AppConstVars.isDownLoadFile) AppConstVars.downLoadFile.StartDown();
        }

        private void SetFoodPageState()
        {
            layFoodType.SetFoodPageState();

            if (AppConstVars.systemsetup.foodTypeBindType >= (int)GlobalEnumVars.FoodTypeBindType.ParentAndChild)
            {
                var pgControl = fly_foodlist.Get(GetFoodItemName(999));
                var itemPage = (UIGoodsPagination)pgControl;
                if (itemPage != null)
                {
                    itemPage.BtnFoodPreState = layFoodType.GetFoodPreState;
                    itemPage.BtnFoodNextState = layFoodType.GetFoodNextState;
                }
            }
        }
        #endregion

        #region 表格（点菜单）绑定相关

        private MenuItemInfo BindOrderingItemInfo(corecmsfoodordering item)
        {
            MenuItemInfo info = new MenuItemInfo();
            info.Count = item.quantity.ToString("0.###");
            info.UnitName = item.unitName;
            info.Price = item.price.ToString("0.0##");
            info.RealPrice = item.realPrice.ToString("0.0##");
            info.Code = item.code;
            info.RowId = item.rowId.ToString();
            if (item.foodPackId > 0)
            {
                info.Name = ">" + item.name;
                //info.ForeColor = Color.Gray;
                info.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(69)))), ((int)(((byte)(120)))), ((int)(((byte)(103)))));
                if (item.allAmount == 0) info.Money = "";
                else info.Money = item.allAmount.ToString("0.0##");
            }
            else
            {
                info.Name = item.name;
                info.Money = item.allAmount.ToString("0.0##");

                //已下单的商品颜色
                if ((item.itemStatus == (int)OrderingItemStatus.TobePlaced) && (orderingMaster != null) && (orderingMaster.deskId > 0))
                    info.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(198)))), ((int)(((byte)(74)))), ((int)(((byte)(0)))));
            }

            if (item.dataType == (int)GlobalEnumVars.OrderingDataType.Refund) info.IsReturning = true;
            if (item.dataType == (int)GlobalEnumVars.OrderingDataType.Present) info.IsPresent = true;
            info.Tags.Clear();
            if (!string.IsNullOrEmpty(item.taskTitle)) info.Tags.Add("做法：" + item.taskTitle);
            if (!string.IsNullOrEmpty(item.feedTitle)) info.Tags.Add("加料：" + item.feedTitle);
            if (!string.IsNullOrEmpty(item.parcel)) info.Tags.Add(string.Format("营业员：{0}",item.parcel));
            if (item.callType > (int)GlobalEnumVars.CallType.Default)
                info.Tags.Add(EnumHelper.GetDescByValue<GlobalEnumVars.CallType>(item.callType));
            if (!string.IsNullOrEmpty(item.remark)) info.Tags.Add("备注：" + item.remark);
            return info;
        }

        private void BindOrdering(long orderId)
        {
            try
            {
                layOrdering.Visible = false;
                pnl_left_number.Text = "0";
                layOrdering.Clear();
                orderingDetail = new corecmsfoodorderingServices().QueryByOrderId(orderId);
                var orderingfoodList = new corecmsfoodServices().QueryByIdsAsync(orderingDetail.Select(p => p.foodId).ToList());
                if ((orderingDetail == null) || (orderingDetail.Count == 0))
                {
                    orderingSelected = null;
                    layOrdering.Panel.BackgroundImage = Resources.NoShopping;
                    layOrdering.Panel.BackgroundImageLayout = ImageLayout.Center;
                } 
                else
                {
                    layOrdering.Panel.BackgroundImage = null;
                }                
                uiMenuItemSelected = null;                
                foreach (var item in orderingDetail)
                {
                    item.foodImage = orderingfoodList.Find(p => p.id.Equals(item.foodId)).image;
                    this.layOrdering.SuspendLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
                    MenuItemInfo info = BindOrderingItemInfo(item);
                    UIMenuItem menu = new UIMenuItem(info);
                    menu.Name = GetMenuItemName(item.id);
                    menu.Margin = new System.Windows.Forms.Padding(0);
                    menu.Tag = item.id;
                    menu.Click += MenuItem_Click;
                    layOrdering.Add(menu);
                    layOrdering.Panel.ScrollControlIntoView(menu); //滚动条拉到最下面
                    this.layOrdering.ResumeLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
                    if (orderingSelected == null) orderingSelected = item;
                    if (orderingSelected.id == item.id)
                    {
                        uiMenuItemSelected = menu;
                        pnl_left_number.Text = orderingSelected.quantity.ToString("0.##");
                        GetItemStatus(item);
                    }
                }

                if (uiMenuItemSelected != null) uiMenuItemSelected.Selected = true;
                RefreshOrderingMaster(orderId);                
                if (Program.frmCustShow != null) Program.frmCustShow.SetCustShowInfo(true);
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "系统出错-BindOrdering:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
            finally
            {
                layOrdering.Visible = true;
            }
            int ScrollWidth = this.layOrdering.VerticalScroll.Maximum;
            this.layOrdering.AutoScrollPosition = new Point(0, ScrollWidth);
        } 

        /// <summary>
        /// 刷新绑定单行数据，不必清除再新增控件
        /// </summary>
        /// <param name="orderId"></param>
        private void BindOrderingRow(corecmsfoodordering item)
        {
            try
            {
                if (item == null)
                {
                    if (orderingMaster != null)
                    {
                        BindOrdering(orderingMaster.orderId);
                    }
                    else
                    {
                        layOrdering.Clear();
                    }
                    return;
                }
                var mControl = layOrdering.Get(GetMenuItemName(item.id));
                var menu = (UIMenuItem)mControl;
                MenuItemInfo info = menu.Info;
                info.Name = item.name;
                info.Count = item.quantity.ToString("0.##");
                info.Money = item.allAmount.ToString("0.##");
                info.Price = item.price.ToString("0.##");
                info.RealPrice = item.realPrice.ToString("0.##");
                info.RowId = item.rowId.ToString();
                if (item.foodPackId > 0)
                {
                    info.Name = ">" + item.name;
                    info.ForeColor = Color.Gray;
                    //info.Money = "";
                }
                else
                {
                    info.Name = item.name;
                    info.Money = item.allAmount.ToString("0.##");
                }
                if (item.dataType == (int)GlobalEnumVars.OrderingDataType.Refund) info.IsReturning = true;
                if (item.dataType == (int)GlobalEnumVars.OrderingDataType.Present) info.IsPresent = true;
                info.Tags.Clear();
                if (!string.IsNullOrEmpty(item.taskTitle)) info.Tags.Add("做法：" + item.taskTitle);
                if (!string.IsNullOrEmpty(item.feedTitle)) info.Tags.Add("加料：" + item.feedTitle);
                if (!string.IsNullOrEmpty(item.parcel)) info.Tags.Add("<打包>");
                if (item.callType > (int)GlobalEnumVars.CallType.Default)
                    info.Tags.Add(EnumHelper.GetDescByValue<GlobalEnumVars.CallType>(item.callType));
                if (!string.IsNullOrEmpty(item.remark)) info.Tags.Add("备注：" + item.remark);
                layOrdering.Refresh();
                RefreshOrderingMaster(orderingMaster.orderId);
                var orderSel = orderingDetail.Find(p => p.id == item.id);
                if (orderSel != null)
                {
                    orderSel.quantity = item.quantity;//这样同步，刷新副屏
                    orderSel.allAmount = item.allAmount;
                }
                if (Program.frmCustShow != null) Program.frmCustShow.SetCustShowInfo(true);
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "系统出错-BindOrdering:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
        }

        #endregion 

        #region 做法与加料

        /// <summary>
        /// 商品做法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetTask_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            if (!IsOrderSelected()) return;
            try
            {
                TimerFocusState(false);
                var frm = new frmfoodtask();
                frm.Owner = this;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (frm.taskType == 0)
                        BindOrdering(orderingSelected.orderId);
                    else
                        BindOrderingRow(orderingSelected);
                }
                frm.Dispose();
            }
            catch { }
            finally { TimerFocusState(true); }
        }


        /// <summary>
        /// 判断是否有选择行,modifyFlag = true时要修改，
        /// </summary>
        /// <returns></returns>
        private bool IsOrderSelected(bool modifyFlag = false)
        {
            if (orderingSelected == null)
            {
                ShowInfoTip("没有选择行,无法操作。");
                return false;
            }
            if ((modifyFlag) && (orderingSelected.itemStatus == (int)OrderingItemStatus.PreSettled))
            {
                ShowInfoTip("该商品已下单,无法操作");
                return false;
            }
            if ((modifyFlag) && (orderingSelected.itemType == (int)GlobalEnumVars.FoodType.PackChild))
            {
                ShowInfoTip("套餐内商品,无法操作");
                return false;
            }
            return true;
        }

        private void btnSetFeed_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            if (!IsOrderSelected()) return;
            try
            {
                TimerFocusState(false);
                var frm = new frmfoodfeed();
                frm.Owner = this;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    BindOrderingRow(orderingSelected);
                }
                frm.Dispose();
            }
            catch { }
            finally { TimerFocusState(true); }

        }
        #endregion


        public async void BindOrderingMaster(long deskId, long orderId = 0)
        {
            btnCashPay.FillColor = btnOrderingCheck.FillColor;
            if (deskId == (int)GlobalEnumVars.OrderDeskType.OrderingPos)
                orderingMaster = new corecmsfoodorderingmasterServices().GetOrderingMaster(0, AppConstVars.sysUser, AppConstVars.classId, AppConstVars.sysUser.storeId);//快餐模式
            else
                orderingMaster = new corecmsfoodorderingmasterServices().QueryByDeskId(deskId, orderId);//开台模式

            if (orderingMaster == null) return;
            //已预结
            if (orderingMaster.status == (int)GlobalEnumVars.TableStatus.PreSettled)
                btnCashPay.FillColor = Color.FromArgb(255, 205, 100);

            orderingSelected = null;
            BindOrdering(orderingMaster.orderId);
            var desk = new corecmsfooddeskServices().GetById(deskId);
            if (desk != null)
                lblDeskName.Text = CommFunc.FormatDeskSpellNumber(desk.name, orderingMaster.number);

            if ((orderingMaster.userId > 0) && (orderingDetail != null) && (orderingDetail.Count > 0))
            {
                //var locaMember = new corecmsuserServices().SelectUserById(CommFunc.ConvertToInt64(orderingMaster.userId));
                //if (locaMember != null)
                //{
                //await GetMemberByIdAsync(locaMember.mobile);  
                //}
                await GetMemberByIdAsync(CommFunc.ConvertToInt64(orderingMaster.userId));  
            }
            else
            {
                orderingMaster.userId = 0;
                orderingMember = null;
                GetEmployeeInfo(null);
            }
            GetMemberInfo(false);
            //BindFoodList(0);
            TimerFocusState(true);
            this.txtInput.Focus();
        }

        public void GetEmployeeInfo(corecmsemployee _employee)
        {
            orderingEmployee = _employee;
            pnl_left_employee.Text = "";
            btnSelectEmp.Tag = "";
            if ((orderingEmployee == null) && (AppConstVars.systemsetup.employeeSelType == (int)GlobalEnumVars.EmployeeSelType.AutoSelect))
            {
                orderingEmployee = new corecmsemployeeServices().GetDefaultEmployee();
            }
            if (orderingEmployee != null)
            {
                pnl_left_employee.Text = orderingEmployee.name + " " + orderingEmployee.mobile;
            }
        }

        private void SetRowModifyState(bool isModify)
        {
            btnCutQty.Enabled = isModify;
            btnAddQty.Enabled = isModify;
            btnRemoveRow.Enabled = isModify;
            btnSetFeed.Enabled = isModify;
            btnSetTask.Enabled = isModify;
            btnRefund.Enabled = !isModify;
            if (orderingSelected == null) return;

            if (string.IsNullOrEmpty(orderingSelected.parcel))
                btnParcel.Text = "打包";
            else
                btnParcel.Text = "取消打包";
            if (orderingSelected.dataType == (int)GlobalEnumVars.OrderingDataType.Present)
                btnPresent.Text = "取消赠送";
            else
                btnPresent.Text = "赠送";

            //套餐商品
            if (orderingSelected.itemType == (int)GlobalEnumVars.FoodType.PackFood)
            {
                btnSetTask.Enabled = false;
                btnSetFeed.Enabled = false;
            }
            //套餐内商品
            if (orderingSelected.foodPackId > 0)
            {
                btnPresent.Enabled = false;
                btnSetDiscount.Enabled = false;
                btnRemoveRow.Enabled = false;
                btnCutQty.Enabled = false;
                btnAddQty.Enabled = false;
                btnRefund.Enabled = false;
            }
            else
            {
                btnPresent.Enabled = true;
                btnSetDiscount.Enabled = true;
            }
            if ((orderingSelected.dataType == (int)GlobalEnumVars.OrderingDataType.Refund)
                || (orderingSelected.itemStatus == (int)OrderingItemStatus.TobePlaced))
            {
                btnRefund.Enabled = false;
            }
        }

        public void RefreshOrderingMaster(long orderId)
        {
            lblAllAmount.Text = "0.00";
            lblSumQuantity.Text = string.Format("共{0}项", 0);
            lblAmount.Text = "0";
            orderingMaster = new corecmsfoodorderingmasterServices().GetForUpdateOrderingMaster(orderId, AppConstVars.systemsetup.sumAmountDecimal);
            if (orderingMaster != null)
            {
                lblAllAmount.Text = orderingMaster.sumAllAmount.ToString("#0.0#");
                lblSumQuantity.Text = string.Format("共{0}项", orderingMaster.foodCount);
                lblAmount.Text = (orderingMaster.sumAmount + orderingMaster.sumFeedAmount + orderingMaster.sumTaskAmount - orderingMaster.sumPresentAmount).ToString("0.0#");
                CustomerDisplay.SetLedShow(lblAllAmount.Text, 2);
            }
            if (orderingDetail == null || orderingDetail.Count == 0)
                btnOrderHand.Text = "取单";
            else
                btnOrderHand.Text = "挂单";
        }

        /// <summary>
        /// 刷新当前行，多站点时必要
        /// </summary>
        public bool GetOrderingSelected()
        {
            if (orderingSelected == null) return false;
            if (!AppConstVars.isMoreSite) return false;
            long orderingId = orderingSelected.id;
            orderingSelected = new corecmsfoodorderingServices().GetById(orderingId);
            if (orderingSelected == null)
            {
                if (orderingMaster != null)
                {
                    BindOrdering(orderingMaster.orderId);
                }
                else
                {
                    layOrdering.Clear();
                }
            }
            if (orderingSelected != null)
                return true;

            return false;
        }

        private void GetItemStatus(corecmsfoodordering entry)
        {
            if (entry.itemStatus == 0)
            {
                SetRowModifyState(true);
            }
            else
            {
                SetRowModifyState(false);
            }
        }

        /// <summary>
        /// 保存数据，
        /// </summary>
        /// <param name="type">type=0全部保存，type=1，保存选择行</param>
        /// <param name="editFieldType">1修改数量，2修改单价，3修改金额，4修改折扣</param>
        private void SaveOrdering(int saveType, int editFieldType)
        {
            bool bl = false;

            //修改数量，计算金额
            if ((editFieldType == 1) || (editFieldType == 2))
            {
                orderingSelected.amount = orderingSelected.quantity * orderingSelected.price;
                orderingSelected.realAmount = CommFunc.GetRowAmount(orderingSelected.quantity * orderingSelected.realPrice, AppConstVars.systemsetup.rowAmountDecimal);
                orderingSelected.taskAmount = new corecmsfoodorderingtaskServices().GetOrderingTaskAmount(orderingSelected);
                orderingSelected.allAmount = CommFunc.GetRowAmount(orderingSelected.realAmount + orderingSelected.taskAmount + orderingSelected.feedAmount, AppConstVars.systemsetup.rowAmountDecimal);
            }
            if (saveType == 1)
            {
                bl = new corecmsfoodorderingServices().SaveOrderingSelected(orderingSelected);
                if (!bl)
                    UIMessageBox.Show("选择行保存失败。", "系统出错-SaveOrdering:", UIStyle.Orange, UIMessageBoxButtons.OK);
                else
                {
                    //促销计算(第二件半价与第二件0元计算）
                    if (new ActivitieUtil().SetOrderingTheSecondPiece(orderingDetail,orderingSelected, orderingMember))
                    {
                        BindOrdering(orderingSelected.orderId);
                    }
                    orderingSelected = new corecmsfoodorderingServices().GetById(orderingSelected.id);
                    BindOrderingRow(orderingSelected);
                }
            }
            else
            {
                bl = new corecmsfoodorderingServices().UpdateRange(orderingDetail);
                if (!bl)
                    UIMessageBox.Show("订单数据保存失败。", "系统出错-SaveOrdering:", UIStyle.Orange, UIMessageBoxButtons.OK);
                else
                    BindOrdering(orderingSelected.orderId);
            }            
        }

        public void AddDataRow(long foodId,long specId, decimal hQty, bool isPlayVoice = false)
        {
            if (orderingMaster == null)
            {
                UIMessageBox.Show("所选择的未开单成功，添加失败。", "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            try
            {
                this.Invoke(new Action(() =>
                {
                    TimerFocusState(false);
                    GetEmployeeInfoAuto();//手动选择营业员

                    string msgStr = "所选择的商品不存在或没有选择商品规格。";
                    decimal weight = CommFunc.ConvertToDecimal(this.lblScaleQty.Text);
                    var ordering = ProcessUtil.CreateByFoodId(Program.frmMainWin, orderingMaster, foodId, specId, hQty, orderingMember, orderingEmployee, ref msgStr, weight);
                    if (ordering == null)
                    {
                        if (!msgStr.IsNullOrEmpty()) UIMessageBox.Show(msgStr, "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                        this.txtInput.Clear();
                        this.txtInput.Focus();
                        return;
                    }
                    if (ordering.quantity == 0) return;

                    Program.frmMainWin.SetClearScale();//清理电子秤缓存

                    this.txtInput.Clear();
                    this.txtInput.Focus();
                    if ((orderingMaster.deskId == (int)GlobalEnumVars.OrderDeskType.OrderingPos) 
                    && (AppConstVars.systemsetup.orderNumberType == (int)GlobalEnumVars.OrderNumberType.Before))
                        SetDeskNumber(false);

                    //ordering.realPrice = CommFunc.GetRowAmount(ordering.realPrice, AppConstVars.systemsetup.rowAmountDecimal);
                    ordering.realAmount = CommFunc.GetRowAmount(ordering.realPrice * ordering.quantity, AppConstVars.systemsetup.rowAmountDecimal);
                    ordering.orderId = orderingMaster.orderId;
                    if (!new OrderingUtil().IsValidError(ordering)) return;
                    long orderingId;
                    if (ordering.id > 0)
                    {
                        orderingId = ordering.id;
                        new corecmsfoodorderingServices().InsertOrUpdateAsync(ordering);
                    }
                    else
                    {
                        orderingId = new corecmsfoodorderingServices().InsertReturnBigIdentity(ordering);
                        ordering.id = orderingId;
                    }

                    //促销计算(第二件半价与第二件0元计算）
                    new ActivitieUtil().SetOrderingTheSecondPiece(orderingDetail, ordering, orderingMember);

                    orderingSelected = new corecmsfoodorderingServices().QueryById(orderingId);
                    if (orderingSelected == null)
                    {
                        UIMessageBox.Show("保存失败", "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                        return;
                    }

                    BindOrdering(orderingMaster.orderId);
                    LoadLastBill(0);
                    if (isPlayVoice) SoundHelper.SetAiGoodsVoice(ordering);//语音播报 
                }));                
            }
            catch (Exception ex) 
            {
                UIMessageBox.Show(ex.Message);            
            }
            finally { TimerFocusState(true); }
        }

        public void GetEmployeeInfoAuto()
        {
            if (AppConstVars.systemsetup.employeeSelType == (int)GlobalEnumVars.EmployeeSelType.SelectAtAddRow)
            {
                btnSelectEmp_Click(null, null);//每行自动选择营业员
            } 
            else
            {
                if ((orderingDetail == null || orderingDetail.Count == 0)
                && (AppConstVars.systemsetup.employeeSelType == (int)GlobalEnumVars.EmployeeSelType.SelectAtNewBill))
                    btnSelectEmp_Click(null, null);//每单自动选择营业员
            }                        
        }

        private void AddDataRowWeighing(corecmsfoodordering ordering)
        {
            if (orderingMaster == null)
            {
                UIMessageBox.Show("所选择的未开单成功，添加失败。", "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            ordering.orderId = orderingMaster.orderId;
            long orderingId;
            if (ordering.id > 0)
            {
                orderingId = ordering.id;
                new corecmsfoodorderingServices().InsertOrUpdateAsync(ordering);
            }
            else
            {
                orderingId = new corecmsfoodorderingServices().InsertReturnBigIdentity(ordering);
            }
            orderingSelected = new corecmsfoodorderingServices().QueryById(orderingId);
            if (orderingSelected == null)
            {
                UIMessageBox.Show("保存失败", "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            BindOrdering(orderingMaster.orderId);
            txtInput.Text = string.Empty;
            txtInput.Focus();
        }
        private async void Item_MouseDown(object sender, System.EventArgs e)
        {
            await Task.Run(() => {
                UIDishItem item = (UIDishItem)sender;
                AddDataRow(CommFunc.ConvertToBigInt(item.Tag), 0, 1);
            });
        }

        private void Item_Click(object sender, System.EventArgs e)
        {
            //UIDishItem item = (UIDishItem)sender;
            //AddDataRow(CommFunc.ConvertToBigInt(item.Tag), 0, 1);
        }

        private void sbtHome_Click(object sender, EventArgs e)
        {
            Program.frmMainWin.SetMainwinClose();

            //if (AppConstVars.systemsetup.orderingMode == (int)GlobalEnumVars.OrderingMode.FastFood)
            //{
            //    Program.frmMainWin.ShowNavigation();
            //}
            //else
            //    Program.frmMainWin.ShowTables();
        }

        private void btnSetDiscount_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            if (!IsOrderSelected(true)) return;
            var foodspec = new corecmsfoodspecServices().GetById(orderingSelected.foodSpecId);
            if (((foodspec == null) || (foodspec.disItem == false)) && (!AppConstVars.systemsetup.isDiscountAll))
            {
                UIMessageBox.Show("选择的商品不允许折扣。", "提示:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }            
            SetDiscounts((int)GlobalEnumVars.DiscountMode.Discount);
        }

        private void SetDiscounts(int type)
        {
            if (!IsOrderSelected()) return;            
            try
            {
                TimerFocusState(false);
                var frm = new frmDiscounts(orderingSelected, type);
                frm.lbl_caption.Text = orderingSelected.name;
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    DoDiscounts(frm.dicountInfo);
                }
                frm.Dispose();
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void DoDiscounts(DicountInfo info)
        {
            try
            {
                GetOrderingSelected();
                if (!IsOrderSelected()) return;
                if (new OrderingUtil().UpdateDiscount(orderingSelected, info) == false)
                {
                    UIMessageBox.Show("打折保存失败", "错误：", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                BindOrdering(orderingSelected.orderId);
                string msg = EnumHelper.GetDescByValue<GlobalEnumVars.DiscountMode>(info.Type) + "成功。";
                ShowInfoTip(btnSetDiscount, msg);
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "错误：", UIStyle.Green, UIMessageBoxButtons.OK);
            }
        }

        private void MenuItem_Click(object sender, System.EventArgs e)
        {
            uiMenuItemSelected = (UIMenuItem)sender;
            long id = CommFunc.ConvertToInt64(uiMenuItemSelected.Tag);
            orderingSelected = new corecmsfoodorderingServices().QueryById(id);
            if (orderingSelected == null)
            {
                UIMessageBox.Show("获取数据失败", "系统提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            pnl_left_number.Text = orderingSelected.quantity.ToString("0.##");
            orderingSelected.quantity = pnl_left_number.Text.ObjToInt(0);
            GetItemStatus(orderingSelected);
        }

        private void btnAddQty_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            if (!IsOrderSelected(true)) return;
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isModifyRow, 0)) return;

            if ((orderingSelected.quantity + 1 > orderingSelected.limitBuyQty) && (orderingSelected.limitBuyQty > 0))
            {
                ShowInfoTip("已超过限购数量,无法操作");
                return;
            }
            if ((orderingSelected.sourceId > 0) && (orderingSelected.dataType == (int)OrderingDataType.ActivityGift || orderingSelected.dataType == (int)OrderingDataType.Present))
            {
                ShowInfoTip("赠送促销，无法直接修改数量");
                return;
            }
            pnl_left_number.Text = (pnl_left_number.Text.ObjToDecimal() + 1).ToString();
            orderingSelected.quantity = pnl_left_number.Text.ObjToDecimal(0);
            SaveOrdering(1, 1);
            orderingDetail.Find(p => p.id == orderingSelected.id).quantity = orderingSelected.quantity;
        }

        private void btnCutQty_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            if (!IsOrderSelected(true)) return;
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isModifyRow, 0)) return;
            if (pnl_left_number.Text.ObjToDecimal() > 1)
            {
                decimal newQty = pnl_left_number.Text.ObjToDecimal() - 1;
                if (!new OrderingUtil().IsOrderingModify(orderingDetail, orderingSelected, newQty, (int)OrderingOperate.CutQty)) return;

                pnl_left_number.Text = newQty.ToString();
                orderingSelected.quantity = pnl_left_number.Text.ObjToDecimal(0);
                SaveOrdering(1, 1);
            }
            orderingDetail.Find(p => p.id == orderingSelected.id).quantity = orderingSelected.quantity;
        }

        private void btnRemoveRow_Click(object sender, EventArgs e)
        {
            if (!IsOrderSelected(true)) return;
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isRemoveRow, 0)) return;

            //p.sourceId == ordering.id说明该行已有促销
            var orderingChild = orderingDetail.Where(p => p.sourceId == orderingSelected.id).ToList();
            if (orderingChild.Any())
            {
                string msg = "已有关联的促销订单明细数据,无法删除，请先删除关联的明细。";
                UIMessageBox.Show(msg, "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                return;
            }

            if (!ShowAskDialog("确认要删除当前选择的商品吗？")) return;

            long orderId = orderingSelected.orderId;
            var bl = new corecmsfoodorderingServices().DeleteBySelected(orderingSelected);
            orderingSelected = null;
            if (bl) BindOrdering(orderId);
        }

        /// <summary>
        /// 判断是否有选择行,modifyFlag = true时要修改，
        /// </summary>
        /// <returns></returns>
        private bool IsOrderingMaster()
        {
            if (orderingMaster == null)
            {
                ShowInfoTip("没有开单,无法操作");
                return false;
            }
            if (AppConstVars.classId == 0)
            {
                ProcessUtil.GetClassData(AppConstVars.sysUser.id);
                if (AppConstVars.classId == 0)
                {
                    UIMessageBox.Show("当前用户没有当班,无法结算", "系统提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
            }
            return true;
        }

        private void SetPayment(string mPayCode, int mPayType)
        {
            if (!IsOrderingMaster()) return;
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isSettlement, 0)) return;
            try
            {
                TimerFocusState(false);
                if (AppConstVars.systemsetup.isKitchen) btnOrderingCheck_Click(null, null);

                if ((orderingMaster.deskId == (int)GlobalEnumVars.OrderDeskType.OrderingPos) 
                    && (AppConstVars.systemsetup.orderNumberType == (int)GlobalEnumVars.OrderNumberType.Afler))
                    SetDeskNumber(false);
                long orderId = orderingMaster.orderId;
                new corecmsdiscountrulesServices().SetOrderingDiscount(orderId);//促销计算
                var frm = new frmSetBalance(orderingMember, orderingMaster.orderId, mPayCode, mPayType);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    BindOrderingMaster(0);
                    LoadLastBill(orderId);
                }

                RefreshOrderingMaster(orderingMaster.orderId);
                frm.Dispose();
                txtInput.Text = "";                
            }
            catch (Exception ex) { }
            finally { TimerFocusState(true); }
        }

        private void btnSetPayment_Click(object sender, EventArgs e)
        {            
            SetPayment("",-1);
        }

        private void btnRowRemark_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            if (!IsOrderSelected()) return;
            try
            {
                TimerFocusState(false);
                var frm = new frmfoodtag();
                frm.Owner = this;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (frm.remarkType == 1)
                        BindOrderingRow(orderingSelected);
                    else BindOrdering(orderingSelected.orderId);
                }
                frm.Dispose();
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void btnOrderData_Click(object sender, EventArgs e)
        {
            try
            {
                TimerFocusState(false);
                long orderId = 0;
                if (orderingMaster != null) orderId = orderingMaster.orderId;
                var frm = new frmOrderingData(orderId, orderingMaster.deskId);
                frm.ShowDialog();
                frm.Dispose();
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void btnParcel_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            if (orderingSelected == null)
            {
                ShowInfoTip("没有选择行,无法标记打包。");
                return;
            }
            if (string.IsNullOrEmpty(orderingSelected.parcel))
            {
                orderingSelected.parcel = "打包";
                btnParcel.Text = "取消打包";
            }
            else
            {
                orderingSelected.parcel = "";
                btnParcel.Text = "打包";
            }
            var bl = new corecmsfoodorderingServices().InsertOrUpdate(orderingSelected);
            if (!bl)
            {
                UIMessageBox.Show("保存失败。", "系统出错-btnParcel_Click:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            BindOrderingRow(orderingSelected);
        }

        private void btnPresent_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            if (!IsOrderSelected()) return;
            if (orderingSelected.dataType == (int)GlobalEnumVars.OrderingDataType.Refund)
            {
                ShowInfoTip("退货明细，不允许赠送。");
                return;
            }
            var foodInfo = new corecmsfoodServices().GetById(orderingSelected.foodId);
            if ((foodInfo == null) || (foodInfo.addSell == 1))
            {
                UIMessageBox.Show("选择的商品不允许赠送。", "提示:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isProductGift, 0)) return;
            if ((orderingSelected.quantity > 1) && (orderingSelected.dataType != (int)GlobalEnumVars.OrderingDataType.Present))
            {
                try
                {
                    TimerFocusState(false);
                    var frm = new frmFoodPresent(orderingSelected);
                    frm.Owner = this;
                    if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        BindOrdering(orderingMaster.orderId);
                    }
                    frm.Dispose();
                }
                catch { }
                finally { TimerFocusState(true); }
                return;
            }

            if (orderingSelected.dataType == (int)GlobalEnumVars.OrderingDataType.Present)
            {
                orderingSelected.dataType = (int)GlobalEnumVars.OrderingDataType.Normal;
                orderingSelected.realPrice = orderingSelected.sourcePrice;
                btnPresent.Text = "赠送";
            }
            else
            {
                orderingSelected.dataType = (int)GlobalEnumVars.OrderingDataType.Present;
                orderingSelected.sourcePrice = orderingSelected.realPrice;
                orderingSelected.realPrice = 0;
                btnParcel.Text = "取消赠送";
            }
            orderingSelected.realAmount = CommFunc.GetRowAmount(orderingSelected.realPrice * orderingSelected.quantity, AppConstVars.systemsetup.rowAmountDecimal);
            orderingSelected.allAmount = CommFunc.GetRowAmount(orderingSelected.realAmount + orderingSelected.feedAmount + orderingSelected.taskAmount, AppConstVars.systemsetup.rowAmountDecimal);
            var bl = new corecmsfoodorderingServices().InsertOrUpdate(orderingSelected);
            if (!bl)
            {
                UIMessageBox.Show("保存失败。", "系统出错-btnGive_Click:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            BindOrdering(orderingSelected.orderId);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                if ((orderingMaster == null) || (orderingDetail == null) || (orderingDetail.Count == 0))
                {
                    ShowInfoTip("没有开单,无法操作");
                    return;
                }
                if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isCancelShopping, 0)) return;

                if (!ShowAskDialog("确认要取消本单数据吗？")) return;
                orderingMember = null;
                orderingMaster.userId = 0;
                GetMemberInfo(true);
                GetEmployeeInfo(null);
                var orderId = orderingMaster.orderId;
                //var bl = new corecmsfoodorderingServices().Delete(p => p.orderId == orderId);
                var bl = new corecmsfoodorderingmasterServices().CancelByIdAsync(orderId);
                orderingSelected = null;
                if (bl) BindOrdering(orderId);
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "提示:", UIStyle.Orange, UIMessageBoxButtons.OK);
            }
        }
        
        private void FOrdering_Activated(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
        }

        public void GetMemberInfo(bool isSetOrderingData)
        {
            long oldMemberId = CommFunc.ConvertToInt64(btnGetMember.Tag);
            long newMemberId = 0;           
            if (orderingMember != null)
            {
                uiMemberInfo.Visible = true;
                newMemberId = orderingMember.id;
                uiMemberInfo.pnlName.Text = orderingMember.userName;
                uiMemberInfo.pnlPhone.Text = orderingMember.mobile;
                uiMemberInfo.pnlAmount.Text = orderingMember.balance.ToString("#0.0#");
                uiMemberInfo.pnlPoints.Text = orderingMember.point.ToString();
                uiMemberInfo.palCustName.Text = orderingMember.gradeName;
            }
            else
            {
                uiMemberInfo.Visible = false;
                if (orderingMaster != null) orderingMaster.userId = 0;
            }
            if ((oldMemberId != newMemberId) && (isSetOrderingData))
            {
                var bl = new MemberUtil().SetMemberData(orderingMaster.orderId, orderingMember);
                RefreshOrderingMaster(orderingMaster.orderId);
                BindOrdering(orderingMaster.orderId);
            }
            btnGetMember.Tag = newMemberId.ToString();
        }

        private void btnGetMember_Click(object sender, EventArgs e)
        {
            GetMemberInfo("");
        }

        private async Task GetMemberByIdAsync(long sMemberId)
        {
            ShowWaitForm("正在加截会员信息，请稍后......");
            try
            {
                orderingMember = await MemberApiUtil.GetListVipInfoById(sMemberId);
                GetMemberInfo(true);
            }
            catch { }
            finally
            {
                HideWaitForm();
            }
        }

        private void GetMemberInfo(string number)
        {
            try
            {
                TimerFocusState(false);
                if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isSelMember, 0)) return;
                var frm = new FrmUserGetInfo(orderingMember, number);
                frm.Owner = this;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    orderingMember = frm.member;
                    GetMemberInfo(true);
                }
                frm.Dispose();
                if (Program.frmCustShow != null) Program.frmCustShow.SetCustShowInfo(true);
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        /// <summary>
        ///显示最后一单
        /// </summary>
        private void LoadLastBill(long orderId)
        {
            this.Invoke(new Action(() =>
            {
                if (orderId == 0)
                {
                    pnl_left_lastBill.Visible = false;
                    return;
                }
                List<corecmsfoodordermaster> listOrder = new corecmsfoodordermasterServices().GetList(p => p.orderId == orderId);
                this.gridLastBill.DataSource = listOrder;
                if (listOrder.Count > 0) pnl_left_lastBill.Visible = true;
            }));
        }

        private void btnOrderingCheck_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isPrintRepair, 0)) return;
            var where = Expressionable.Create<corecmsfoodordermaster>();
            where = where.And(a => a.sysUserId == AppConstVars.sysUser.id);
            where = where.And(a => a.ordertype ==(int)GlobalEnumVars.OrderBillType.Order);
            var orderId = new corecmsfoodordermasterServices().AsQueryable().WhereIF(true, where.ToExpression()).Max(p=>p.orderId);
            if (orderId > 0)
            {
                var orderMaster = new corecmsfoodordermasterServices().GetById(orderId);
                new PrintServices().SetPrintSettlement(orderMaster, false);
            }
            else
            {
                ShowInfoTip($"没有可打印的单据数据");
            }
        }

        /// <summary>
        /// 快餐牌号输入
        /// </summary>
        /// <param name="editFlag"></param>
        private void SetDeskNumber(bool editFlag)
        {
            if (AppConstVars.systemsetup.orderNumberType == (int)GlobalEnumVars.OrderNumberType.Without) return;
            if (!IsOrderingMaster()) return;
            if (orderingMaster.deskId > 0) return;
            if ((!editFlag) && (!string.IsNullOrEmpty(orderingMaster.number))) return;
            try
            {
                TimerFocusState(false);
                var frm = new frmInputNumber(0, "编牌号输入");
                frm.IsNumber = false;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    orderingMaster.number = frm.txtNumber.Text;
                    new corecmsfoodorderingmasterServices().Update(orderingMaster);
                    var desk = new corecmsfooddeskServices().GetById(orderingMaster.deskId);
                    if (desk != null)
                    {
                        lblDeskName.Text = CommFunc.FormatDeskSpellNumber(desk.name, orderingMaster.number);
                    }
                }
                frm.Dispose();
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void lblDeskName_Click(object sender, EventArgs e)
        {
            SetDeskNumber(true);
        }
        private void txtInput_OkButtonClick(object sender, string value)
        {
            //查看秤日志口令
            string showlog = "showlog";
            if (value.Equals(showlog, StringComparison.OrdinalIgnoreCase)) Program.frmMainWin.ShowLog();

            layFoodType.FoodPageIndex = 1;
            BindFoodList(0);
        }

        private void pnl_left_number_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            #region 判断数据项
            if (orderingSelected == null)
            {
                ShowInfoTip("没有选择行,无法操作。");
                return;
            }
            if (orderingSelected.itemType == (int)GlobalEnumVars.FoodType.PackChild)
            {
                ShowInfoTip("套餐内商品,无法操作");
                return;
            }
            if (orderingSelected.itemType == (int)GlobalEnumVars.FoodType.GroupChild)
            {
                ShowInfoTip("配菜明细商品,无法操作");
                return;
            }
            var foodspec = new corecmsfoodspecServices().GetById(orderingSelected.foodSpecId);
            if (foodspec == null)
            {
                ShowInfoTip("该商品规格不存在,无法操作");
                return;
            }
            if ((orderingSelected.sourceId > 0) && (orderingSelected.dataType == (int)OrderingDataType.ActivityGift || orderingSelected.dataType == (int)OrderingDataType.Present))
            {
                ShowInfoTip("赠送促销，无法直接修改数量");
                return;
            }
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isModifyRow, 0)) return;
            #endregion
            try
            {
                TimerFocusState(false);
                frmFoodSpecWeigh foodSpecWeigh = new frmFoodSpecWeigh(orderingSelected, foodspec, false);
                foodSpecWeigh.Owner = Program.frmMainWin;
                if (foodSpecWeigh.ShowDialog() == DialogResult.OK)
                {
                    decimal dQuantity = CommFunc.ConvertToDecimal(foodSpecWeigh.mScaleQty);
                    if (new OrderingUtil().IsOrderingModify(orderingDetail, orderingSelected, dQuantity, (int)OrderingOperate.CutQty))
                    {
                        orderingSelected.specName = foodSpecWeigh.txtSpecName.Text;
                        orderingSelected.quantity = CommFunc.ConvertToDecimal(dQuantity);
                        pnl_left_number.Text = orderingSelected.quantity.ToString("0.##");
                        Program.frmMainWin.SetClearScale();
                        SaveOrdering(1, 1);
                        ShowInfoTip("修改成功。");
                    }
                }
                foodSpecWeigh.Dispose();
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void FOrdering_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void btnOpenMoneyBox_Click(object sender, EventArgs e)
        {
            CustomerDisplay.OpenCashbox();
        }        

        private void FOrdering_ReceiveParams(object sender, UIPageParamsArgs e)
        {
            TimerFocusState(true);
            this.txtInput.Focus();
        }

        private void txtInput_Leave(object sender, EventArgs e)
        {
            isFocusInput = false;
            //timer_focus.Enabled = true;
            //timer_focus.Start();
        }

        private void FOrdering_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!isFocusInput)
            {
                this.txtInput.Focus();

                //SendKeys.Send(e.KeyChar.ToString());
            }
        }

        private void txtInput_Enter(object sender, EventArgs e)
        {
            isFocusInput = true;
            //TimerFocusState(false);
        }

        private void btnSetReduceAmount_Click(object sender, EventArgs e)
        {
            try
            {
                TimerFocusState(false);
                orderingMaster = new corecmsfoodorderingmasterServices().GetForUpdateOrderingMaster(orderingMaster.orderId, AppConstVars.systemsetup.sumAmountDecimal);
                List<corecmsfoodorderingtag> orderingTag = new corecmsfoodorderingtagServices().QueryByOrderId(orderingMaster.orderId);
                var frm = new frmSetReduce(2);
                frm.orderingMaster = orderingMaster;
                frm.orderingTags = orderingTag;
                frm.Owner = this;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    RefreshOrderingMaster(orderingMaster.orderId);
                }
                frm.Dispose();
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void btnChangePrice_Click(object sender, EventArgs e)
        {
            if (!IsOrderSelected()) return;
            var foodInfo = new corecmsfoodspecServices().GetById(orderingSelected.foodSpecId);
            if ((foodInfo == null) || (foodInfo.chgPrice.ObjToBool() == false))
            {
                UIMessageBox.Show("选择的商品不允许改价。", "提示:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }            
            SetDiscounts((int)GlobalEnumVars.DiscountMode.ChangPrice);
        }

        private bool SetAutoPayType(string sCoce)
        {
            if (!AppConstVars.systemsetup.paraPartialModel.mobilePayOnPos) return false;
            if (sCoce.Length > 15)
            {                
                bool isMobelePay = false;//扫码支付
                int mMobilePayId = -1;
                mMobilePayId = new OrderingUtil().GetMobilePayType(sCoce, ref isMobelePay, ref mMobilePayId);
                if (isMobelePay)
                {
                    SetPayment(sCoce, mMobilePayId);
                    return true;
                }
            }
            return false;
        }

        private void SetSearchFoods()
        {            
            int addTime = 0;
            string sCode = txtInput.Text.ToString().Trim();
            if ((sCode == "6") || (sCode == "1")) addTime = -700;//扫描时，第一个6到第二位的9，间隔较长。
            DateTime tempDt = DateTime.Now; //保存按键按下时刻的时间点
            TimeSpan ts = tempDt.Subtract(dLastTime); //获取时间间隔
            if (ts.Milliseconds + addTime > 300)  //200判断时间间隔，如果时间间隔大于50毫秒，则将判断为手工输入
            {
                //清空text数据，且有数据，不重新刷新数据
                if (!IsClearText())
                {
                    layFoodType.FoodPageIndex = 1;
                    BindFoodList(0);
                    Program.frmMainWin.A_SetLog("="+ (ts.Milliseconds + addTime).ToString() + "\n");
                }
            }
            dLastTime = tempDt;
        }

        private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)13) return;
            txtInput.HideDropDown();
            try
            {
                string sCode = txtInput.Text.ToString().Trim();
                if (sCode.IsNullOrEmpty())
                {
                    if (orderingMaster == null) return;
                    if (orderingDetail == null || orderingDetail.Count == 0) return;
                    btnSetPayment_Click(null, null);
                    return;
                }
                if (SetAutoPayType(sCode))
                {
                    e.Handled = true;
                    return;//扫码支付
                }

                //判断是否是生鲜商品
                if (sCode.Length == 13 && sCode.Substring(0, 2) == AppConstVars.systemsetup.weighingCodeSign)
                {
                    corecmsfoodordering ordering = new corecmsfoodordering();
                    if (new OrderingUtil().GetWeighingCode(sCode, ref ordering))
                    {
                        AddDataRowWeighing(ordering);
                        return;
                    }
                }

                corecmsfoodspec corecmsfoodspec = ProcessUtil.GetSpecByFoodCode(this, sCode);
                if (corecmsfoodspec == null)
                {
                    UIMessageBox.Show("所选择的商品不存在或没有选择商品规格。", "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                    this.txtInput.Text = "";
                    return;
                }
                AddDataRow(corecmsfoodspec.foodId, corecmsfoodspec.id, 1);
            }
            catch (Exception ex) { }
            finally { TimerFocusState(true); }
        }

        private async Task GetOrderHandAsync(long orderId)
        {
            BindOrdering(orderId);
            orderingMaster = new corecmsfoodorderingmasterServices().GetForUpdateOrderingMaster(orderId, AppConstVars.systemsetup.sumAmountDecimal);

            if (orderingMaster == null)
                orderingMaster = new corecmsfoodorderingmasterServices().GetOrderingMaster(0, AppConstVars.sysUser, AppConstVars.classId, AppConstVars.sysUser.storeId);//快餐模式

            if (orderingMaster == null)
            {
                UIMessageBox.Show("取单主表失败。");
                return;
            }
            if (CommFunc.ConvertToInt64(orderingMaster.userId) > 0)
            {
                //var locaMember = new corecmsuserServices().SelectUserById(CommFunc.ConvertToInt64(orderingMaster.userId));
                //if (locaMember != null)
                //{
                //    await GetMemberByIdAsync(locaMember.mobile);
                //}
                await GetMemberByIdAsync(CommFunc.ConvertToInt64(orderingMaster.userId));
            }
        }

        private async void btnOrderHand_Click(object sender, EventArgs e)
        {
            try
            {
                TimerFocusState(false);
                if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isHandupShopping, 0)) return;
                if (orderingDetail == null || orderingDetail.Count == 0)
                {
                    //取单操作
                    var frm = new frmOrderingData(0, 0);
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        await GetOrderHandAsync(frm.orderId);
                    }
                    frm.Dispose();
                }
                else
                {
                    //挂单操作
                    if (string.IsNullOrEmpty(orderingMaster.orderNo))
                        orderingMaster.orderNo = ProcessUtil.GetOrderNo((int)GlobalEnumVars.SerialNumberType.订单编号);

                    orderingMaster = new corecmsfoodorderingmasterServices().SetOrderingHangup(orderingMaster,
                        AppConstVars.sysUser, AppConstVars.classId, AppConstVars.sysUser.storeId);//挂起后直接新增一个单

                    uiMemberInfo_exitMember(uiMemberInfo);//退出会员

                    BindOrdering(orderingMaster.orderId);
                }
                btnOrderHand.TipsText = await OrderingUtil.GetHangupsCount();
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void btnOffClass_Click(object sender, EventArgs e)
        {
            try
            {
                TimerFocusState(false);
                Program.frmMainWin.SetOffClass();
            }
            finally { TimerFocusState(true); }            
        }

        private void btnOrderList_Click(object sender, EventArgs e)
        {
            try
            {
                TimerFocusState(false);
                Program.frmMainWin.SetOrderList();
            }
            finally { TimerFocusState(true); }
        }

        private void btnReports_Click(object sender, EventArgs e)
        {
            try
            {
                TimerFocusState(false);
                Program.frmMainWin.ShowReports();
            }
            finally { TimerFocusState(true); }            
        }

        private void btnGoodsList_Click(object sender, EventArgs e)
        {
            try
            {
                TimerFocusState(false);
                var frm = new frmFoodSelect(null);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    corecmsfoodspec corecmsfoodspec = frm.specModel;
                    if (corecmsfoodspec != null)
                        AddDataRow(corecmsfoodspec.foodId, corecmsfoodspec.id, 1);
                }
                frm.Dispose();
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void sbtGotoNavg_Click(object sender, EventArgs e)
        {
            TimerFocusState(false);
            Program.frmMainWin.ShowNavigation();
        }

        private void btnGoodsAI_Click(object sender, EventArgs e)
        {
            if (AppConstVars.systemsetup.aiType == (int)GlobalEnumVars.AiType.None)
            {
                ShowInfoTip("没有设置AI设备,无法操作");
                return;
            }
            //TimerFocusState(false);
            if (aIProductSelect == null || aIProductSelect.IsDisposed)
            {
                aIProductSelect = new frmFoodListAI();
                aIProductSelect.Owner = this;
                //this.setWeighQtyAI += aIProductSelect.GetWeighQtyAI_Selected;
            }
            if (aIProductSelect.Visible == false)
            {
                aIProductSelect.Show();
                aIProductSelect.btnFiler_Click(null, null);
            }
        }

        private void lblScaleQty_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (aIProductSelect != null) aIProductSelect.lblScaleQty.Text = this.lblScaleQty.Text;
                if ((timer_focus.Enabled == true) || (aIProductSelect != null && aIProductSelect.Visible)) 
                {
                    //if (setWeighQtyAI != null) setWeighQtyAI(CommUtil.ConvertDBNullToDecimal(uiLabel1.Text));
                    AI_SetReboot();//AI取数                    
                    return;
                }                
            }
            catch (Exception ex) {
                //MessageBox.Show(ex.Message);
            }
        }

        private void btnGetFoodWeigh_Click(object sender, EventArgs e)
        {
            GetOrderingSelected();
            if (!IsOrderSelected()) return;
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isGetWeigh, 0)) return;
            try
            {
                TimerFocusState(false);
                decimal sQty = orderingSelected.quantity;
                decimal quantity = FoodUtil.GetFoodWeigh(Program.frmMainWin, orderingSelected, ref sQty);
                if (orderingSelected.quantity != quantity)
                {
                    pnl_left_number.Text = quantity.ToString();
                    orderingSelected.quantity = quantity;
                    SaveOrdering(1, 1);
                    orderingDetail.Find(p => p.id == orderingSelected.id).quantity = orderingSelected.quantity;
                }
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void btnPrintLabel_Click(object sender, EventArgs e)
        {
            if (!IsOrderingMaster()) return;
            if (!IsOrderSelected()) return;
            var result = new PrintServices().SetPrintLabelFromOrder(orderingMaster, orderingSelected, false);
            if (result && AppConstVars.systemsetup.paraPartialModel.clearAfterPrint)
            {
                long orderId = orderingSelected.orderId;
                var bl = new corecmsfoodorderingServices().DeleteBySelected(orderingSelected);
                orderingSelected = null;
                if (bl) BindOrdering(orderId);
            }
        }

        private void btnCashPay_Click(object sender, EventArgs e)
        {
            if ((AppConstVars.systemsetup.paraPartialModel.quickPayType == (int)GlobalEnumVars.QuickPayType.MobilePayment)
                    || (AppConstVars.systemsetup.paraPartialModel.quickPayType == (int)GlobalEnumVars.QuickPayType.AliPay_NFC))
            {
                SetPayment("", (int)GlobalEnumVars.Payment.paymix);
                
            }
            else
                SetPayment("", (int)GlobalEnumVars.Payment.cash);
        }

        private DateTime dLastTime = DateTime.Now;  //定义一个成员函数用于保存每次的时间点,用户判断是扫描还是手工录入
        private void txtInput_TextChanged(object sender, EventArgs e)
        {
            //如果键盘打开，启用这个方法执行搜索。DoValueChanged拿不到最后输入的字符，与txtInput_KeyUp切换使用
            if ((txtInput.keyboardForm != null) && (txtInput.keyboardForm.Visible)) SetSearchFoods();
        }

        private void txtInput_KeyUp(object sender, KeyEventArgs e)
        {
            //如果键盘不打开，启用这个方法执行搜索。DoValueChanged拿不到最后输入的字符,与txtInput_TextChanged切换使用
            if ((txtInput.keyboardForm == null) || (!txtInput.keyboardForm.Visible))
            {
                if (e.KeyCode != Keys.Enter) SetSearchFoods();
            }                
        }

        private void btnSelectEmp_Click(object sender, EventArgs e)
        {
            try
            {
                TimerFocusState(false);
                var frm = new frmEmployeeSelect(0);
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    GetEmployeeInfo(frm.selectModel);
                }
                frm.Dispose();
            }
            finally { TimerFocusState(true); }
        }

        private void btnMallOrder_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isOrderList, 0)) return;
            var frm = new frmMallOrderList();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnTempGoods_Click(object sender, EventArgs e)
        {
            try
            {
                TimerFocusState(false);
                corecmsfoodspec corecmsfoodspec = ProcessUtil.GetSpecByTempGoods(this);
                if (corecmsfoodspec == null)
                {
                    UIMessageBox.Show("所选择的临时商品不存在或没有选择商品规格。", "系统提示", UIStyle.Orange, UIMessageBoxButtons.OK);
                    this.txtInput.SelectAll();
                    return;
                }
                AddDataRow(corecmsfoodspec.foodId, corecmsfoodspec.id, 1);
            }
            catch { }
            finally { TimerFocusState(true); }
        }

        private void btnMinimized_Click(object sender, EventArgs e)
        {
           Program.frmMainWin.WindowState = FormWindowState.Minimized;
        }

        private void uiMemberInfo_exitMember(Module.Member.UIMemberInfo gsMemberInfo)
        {
            orderingMember = null;
            GetMemberInfo(true);
            if (Program.frmCustShow != null) Program.frmCustShow.SetCustShowInfo(true);
        }

        private void uiMemberInfo_showMember(Module.Member.UIMemberInfo gsMemberInfo)
        {
            GetMemberInfo("");
        }

        private void btnSetZero_Click(object sender, EventArgs e)
        {
            if (AppConstVars.mScaleType == (int)GlobalEnumVars.ScaleType.DJ_OS2_Dll) DingjianClass.__Zero("1234");
        }

        private void btnMoreMenu_Click(object sender, EventArgs e)
        {
            var frm = new frmMaxFormTest();
            frm.ShowDialog();
            frm.Disabled();

            //var uIDepositary = new UIMoreMenu();
            //UIToolStripDropDown MoreMenu = new UIToolStripDropDown(uIDepositary);
            //MoreMenu.ValueChanged += MoreMenu_ValueChanged;
            //MoreMenu.Show(pnl_center_top_foodtype, 0, 0);
        }

        private void MoreMenu_ValueChanged(object sender, object value)
        {
            if (CommFunc.ConvertToInt32(value) == 1)
            {
                var frm = new frmSelectFoods((int)Library.GlobalEnumVars.BillType.TempStorage, "物品寄存录入");
                frm.ShowDialog();
                frm.Dispose();
            }
        }

    }
}